/**
 * Copyright(C) 2012 Luvina Software Company
 *
 * LoginNameValidator.java, 10/1/2013, bacdv
 */
package net.luvina.manageuser.validator;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import net.luvina.manageuser.util.Message;

/**
 * LoginNameValidator
 *
 * @author bacdv
 *
 */
public class LoginNameValidator implements Validator {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	public void validate(FacesContext context, UIComponent conponent, Object obj)
			throws ValidatorException {
		String loginName = (String) obj;
		String labelItem = (String) conponent.getAttributes().get("label");
		int max = 15;
		int min = 4;
		Pattern patt = Pattern.compile("^[A-Za-z_]{1}[A-Za-z0-9_]+$");
		Matcher match = patt.matcher(loginName);
		boolean matchFound = match.find();
		if (!matchFound) {
			FacesMessage message = new FacesMessage();
			message.setSummary(MessageFormat.format(Message.getString("ER019"),
					labelItem));
			throw new ValidatorException(message);
		} else {
			if (loginName.length() < min || loginName.length() > max) {
				FacesMessage message = new FacesMessage();
				message.setSummary(MessageFormat.format(Message
						.getString("ER007"), labelItem, min, max));
				throw new ValidatorException(message);
			}
		}
	}
}
